package com.example.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.exception.BusinessException;
import com.example.entity.emp.SysUser;
import com.example.entity.emp.SysUserRole;
import com.example.entity.emp.SysRole;
import com.example.mapper.emp.SysUserMapper;
import com.example.mapper.emp.SysUserRoleMapper;
import com.example.mapper.emp.SysRoleMapper;
import com.example.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统用户服务实现类
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Override
    public String login(String username, String password) {
        // 查询用户
        SysUser user = getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username));
        
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 验证密码
        if (!BCrypt.checkpw(password, user.getPassword())) {
            throw new BusinessException("密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() != 1) {
            throw new BusinessException("用户已被禁用");
        }
        
        // 执行登录
        StpUtil.login(user.getId());
        
        // 不再需要手动设置角色列表，StpInterface实现会自动处理
        // StpUtil.getSession().set("role_list", roleList);
        
        // 返回token
        return StpUtil.getTokenValue();
    }

    @Override
    public SysUser getCurrentUser() {
        Long userId = Long.valueOf(StpUtil.getLoginIdAsString());
        return getById(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(SysUser user) {
        // 检查用户名是否已存在
        long count = count(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, user.getUsername()));
        
        if (count > 0) {
            throw new BusinessException("用户名已存在");
        }
        
        // 密码加密
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        
        // 设置初始状态
        user.setStatus(1);
        
        save(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(String oldPassword, String newPassword) {
        // 获取当前用户
        SysUser user = getCurrentUser();
        
        // 验证旧密码
        if (!BCrypt.checkpw(oldPassword, user.getPassword())) {
            throw new BusinessException("原密码错误");
        }
        
        // 更新密码
        user.setPassword(BCrypt.hashpw(newPassword));
        updateById(user);
    }

   

    /**
     * 获取用户角色列表
     */
    private List<String> getUserRoles(Long userId) {
        // 查询用户的角色编码
        // 示例SQL，请根据实际数据库结构调整
        String sql = "SELECT r.role_code FROM sys_role r " +
                     "JOIN sys_user_role ur ON r.id = ur.role_id " +
                     "WHERE ur.user_id = ?";
        
        // 使用MyBatis-Plus进行查询
        List<SysUserRole> userRoles = userRoleMapper.selectList(
            new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId)
        );
        
        if (userRoles == null || userRoles.isEmpty()) {
            return Collections.emptyList();
        }
        
        // 获取角色ID列表
        List<Long> roleIds = userRoles.stream()
            .map(SysUserRole::getRoleId)
            .collect(Collectors.toList());
        
        // 查询角色信息
        List<SysRole> roles = roleMapper.selectList(
            new LambdaQueryWrapper<SysRole>()
                .in(SysRole::getId, roleIds)
        );
        
        // 提取角色编码
        return roles.stream()
            .map(SysRole::getRoleCode)
            .collect(Collectors.toList());
    }
} 